package com.meixiang.activity.account.myAppointment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.myShopper.PhotoFileEvaluateActivity;
import com.meixiang.adapter.personalCenter.OrderEvaluationPhotoAdapter;
import com.meixiang.dialog.AlertDialogFragment;
import com.meixiang.dialog.SelectDialog;
import com.meixiang.entity.EvaluateGradle;
import com.meixiang.entity.servicOrder.TagLabelBeanList;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalConventionalData;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbFileUtils;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.GlideHelper;
import com.meixiang.view.CircleImageView;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.StarLayout;
import com.meixiang.view.TitleView;
import com.meixiang.view.photoSelectActivity.util.Bimp;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author xyj
 *         服务 待评价
 */
public class AppointmentEvaluationActivity extends BaseActivity {
    @Bind(R.id.title)
    TitleView titleView; //头部视图
    @Bind(R.id.order_evaluation_button_commit)
    Button orderEvaluationBottom;
    @Bind(R.id.appointment_evaluation_iv_shopping)
    ImageView ivImageView; //商品图片
    @Bind(R.id.appointment_evaluation_tv_shopping_name)
    TextView tvName; //商品名称
    @Bind(R.id.appointment_evaluation_start)
    StarLayout mStart; //星标
    @Bind(R.id.appointment_evaluation_tv_start_details)
    TextView tvStartDetails; //商品星标描述
    @Bind(R.id.appointment_sale_et_problem_details)
    ClearEditText etSale; // 商品评价
    @Bind(R.id.appointment_sale_linear_photo_printing)
    LinearLayout llPhotoPrint; //添加图片
    @Bind(R.id.beautil_info)
    RelativeLayout beautil_info;
    @Bind(R.id.iv_portrait)
    CircleImageView iv_portrait; // 美容师头像
    @Bind(R.id.tv_evaluation_name)
    TextView tv_evaluation_name; //美容师名称
    @Bind(R.id.tv_evaluation_start)
    StarLayout evaluation_start; //美容师星标
    @Bind(R.id.appointment_portrait_evaluation_start_details)
    TextView portraitText ; //星标对应描述
    @Bind(R.id.order_sale_et_problem_details)
    ClearEditText et_problem;
    @Bind(R.id.fl_selector)
    TagFlowLayout flowLayout;
    @Bind(R.id.grid_recycler)
    RecyclerView gridRecycler;
    private OrderEvaluationPhotoAdapter gridAdapter;
    private ArrayList<String> imageList;
    private static final int CAMERA_CODE = 0x00; // 拍照的权限
    private File imgFile;//相机拍照存放地址
    private DeleteSelectPhotoBroad broadCast;
    private String orderName, typeId, gcId,goodsImage, o2oServiceOrderId, businessId, businessImage, beauticianServiceOrderId;
    private String orderNum, businessNum, businessName;
    private List<String> mLabel;
    private List<EvaluateGradle> evaluateGradleList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_appointment_evaluation);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        registerBroadCast();
    }

    @Override
    protected void initTitle() {
        evaluateGradleList = MXApplication.mApp.getEvaluateGradle();
        if (evaluateGradleList == null) {
            GlobalConventionalData.getEvaluateStart(this);
        }
        titleView.setTitle(R.string.appointment_serve_stay_evaluate_title);
        titleView.setLeftImageButton(R.mipmap.back);
        titleView.showLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialogFragment.Builder()
                        .setContentText("亲，评价还未完成，您确定要离开？")
                        .setLeftBtnText("确认").setLeftClickCallBack(new AlertDialogFragment.LeftClickCallBack() {
                    @Override
                    public void dialogLeftBtnClick() {
                        Bimp.tempSelectBitmap.clear();
                        AppointmentEvaluationActivity.this.finish();
                    }
                }).setRightBtnText("取消")
                        .build()
                        .show(getSupportFragmentManager(), AlertDialogFragment.TAG);

            }
        });
    }

    private void registerBroadCast() {
        broadCast = new DeleteSelectPhotoBroad();
        IntentFilter intentFilter = new IntentFilter(GlobalType.EVALUATE_ORDER_DELETE_PHOTO);
        registerReceiver(broadCast, intentFilter);
    }

    private class DeleteSelectPhotoBroad extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int position = intent.getIntExtra("position", 0);
            gridAdapter.deletePhoto(position);
        }
    }

    /**
     * 刷新订单列表
     */
    private void notifyOrderList(){
        Intent intent=new Intent(GlobalType.APPOINTMENT_DETIAL);
        sendBroadcast(intent);
        this.finish();
    }

    @Override
    protected void initView() {
        imageList = new ArrayList<>();
        orderName = getIntent().getStringExtra("orderName");
        typeId = getIntent().getStringExtra("typeId");
        gcId = getIntent().getStringExtra("gcId");
        o2oServiceOrderId = getIntent().getStringExtra("o2oService.o2oServiceOrderId");
        businessId = getIntent().getStringExtra("beautician.businessId");
        businessImage = getIntent().getStringExtra("businessImage");
        goodsImage = getIntent().getStringExtra("goodimage");
        businessName = getIntent().getStringExtra("businessName");
        beauticianServiceOrderId = getIntent().getStringExtra("beautician.o2oServiceOrderId");
        mLabel = new ArrayList<>();
        mStart.starOnclickListener(new StarLayout.IStarOnclick() {
            @Override
            public void starNumber(int number) {
                if (evaluateGradleList != null) {
                    for (int i = 0; i < evaluateGradleList.size(); i++) {
                        if (number == Integer.parseInt(evaluateGradleList.get(i).getGrade())) {
                            String scoresText = evaluateGradleList.get(i).getDescription();
                            tvStartDetails.setText(scoresText);
                            orderNum = String.valueOf(number);
                        }
                    }
                }
            }
        });
        evaluation_start.starOnclickListener(new StarLayout.IStarOnclick() {
            @Override
            public void starNumber(int number) {
                if (evaluateGradleList != null) {
                    for (int i = 0; i < evaluateGradleList.size(); i++) {
                        if (number == Integer.parseInt(evaluateGradleList.get(i).getGrade())) {
                            String scoresText = evaluateGradleList.get(i).getDescription();
                            businessNum = String.valueOf(number);
                            portraitText.setText(scoresText);
                        }
                    }
                }
            }
        });

        llPhotoPrint.setOnClickListener(this);
        orderEvaluationBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(gcId)) {
                    if (TextUtils.isEmpty(orderNum)){
                        Tool.showTextToast(context, "请给服务评分");
                        return;
                    }
                    if ( TextUtils.isEmpty(etSale.getText().toString())) {
                        Tool.showTextToast(context, "请输入服务评价内容");
                        return;
                    }
                    if (TextUtils.isEmpty(businessNum)){
                        Tool.showTextToast(context, "请给美容师评分");
                        return;
                    }
                    if (tagId.size()==0){
                        Tool.showTextToast(context, "请选择评价标签");
                        return;
                    }
                    if ( TextUtils.isEmpty(et_problem.getText().toString())) {
                        Tool.showTextToast(context, "请输入美容师评价内容");
                        return;
                    }
                    saveServiceEval();
                }else{
                    if (TextUtils.isEmpty(orderNum)){
                        Tool.showTextToast(context, "请给服务评分");
                        return;
                    }
                    if ( TextUtils.isEmpty(etSale.getText().toString())) {
                        Tool.showTextToast(context, "请输入服务评价内容");
                        return;
                    }
                    saveTrainEval();
                }
            }
        });
    }

    @Override
    protected void setData() {
        if ("1".equals(gcId)) {
            getO2oBeauticianEvalLabel();
        }else{
            initLabelView();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.appointment_sale_linear_photo_printing:
                if (imageList.size() >= 4) {
                    Tool.showTextToast(context, "不能超过4张");
                    return;
                }
                new SelectDialog(context, new String[]{"拍照上传", "相册选择"}, new SelectDialog.IResultListener() {
                    @Override
                    public void SelectResult(int result) {

                        if (result == 0) {
                            //拍照
                            if (Build.VERSION.SDK_INT >= 23) {
                                MPermissions.requestPermissions(AppointmentEvaluationActivity.this, CAMERA_CODE, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA});
                            } else {
                                photoGraph();
                            }
                        } else {
                            //手机相册
                            localImage();
                        }
                    }
                });
                break;
        }
    }

    private List<TagLabelBeanList.TagLabelBean> tagList = new ArrayList<>(); //获取标签
    private final List<String> tagId = new ArrayList<>();//保存已选中的标签

    /**
     * 获取美容师评价标签
     */
    private void getO2oBeauticianEvalLabel() {
        HttpParams params = new HttpParams();
        params.put("orderId",o2oServiceOrderId);
        HttpUtils.post(Config.SERVICE_BEAUTICIAN_LABEL, params,new HttpCallBack(this) {
                    @Override
                    public void onSucceed(JSONObject result, String code, String message) {
                        TagLabelBeanList tagLabelBeanList = AbJsonUtil.fromJson(result.toString(), new TypeToken<TagLabelBeanList>() {
                        });
                        if (tagLabelBeanList.getEvalLabels().size() != 0) {
                            for (int i = 0; i < tagLabelBeanList.getEvalLabels().size(); i++) {
                                tagList.add(tagLabelBeanList.getEvalLabels().get(i));
                            }
                            initTagLabel();
                            businessName = tagLabelBeanList.getO2oBeautiName();
                            businessId = tagLabelBeanList.getO2oBeautiId();
                            businessImage = tagLabelBeanList.getO2oBeautiImag();
                            initLabelView();
                        }
                    }

                    @Override
                    public void onError(String code, String message) {
                        Tool.showTextToast(context, message);
                    }
                }
        );
    }

    /**
     * 初始化商品视图
     */
    private void initLabelView(){
        tvName.setText(orderName);
        if (businessImage != null) {
            GlideHelper.showImage(context, businessImage, iv_portrait);
        }
        GlideHelper.showImage(context, goodsImage, ivImageView);
        if (businessName != null) {
            tv_evaluation_name.setText(businessName);
        }
        if ("1".equals(gcId)) {
            beautil_info.setVisibility(View.VISIBLE);
        } else {
            beautil_info.setVisibility(View.GONE);
        }
        gridAdapter = new OrderEvaluationPhotoAdapter(context, orderName);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 4);
        gridRecycler.setLayoutManager(gridLayoutManager);
        gridRecycler.setAdapter(gridAdapter);
    }
    /**
     * 初始化评价标签
     */
    @SuppressWarnings("unchecked")
    private void initTagLabel() {
        TagAdapter styleAdapter = new TagAdapter(tagList) {
            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, Object o) {
                final TextView textView = (TextView) LayoutInflater.from(context).inflate(R.layout.activity_order_evalution_tag, parent, false);
                textView.setTextColor(ContextCompat.getColor(context, R.color.black_8));
                textView.setBackgroundColor(ContextCompat.getColor(context, R.color.order_evaluate_gray_color));
                if (tagList.get(position).isSelected() == true) {
                    tagId.add(tagList.get(position).getEvalLabelName());
                    textView.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
                    textView.setBackgroundColor(ContextCompat.getColor(context, R.color.order_pink_color));
                } else {
                    textView.setTextColor(ContextCompat.getColor(context, R.color.black_8));
                    textView.setBackgroundColor(ContextCompat.getColor(context, R.color.order_evaluate_gray_color));
                    tagId.remove(tagList.get(position).getEvalLabelName());
                }
                textView.setText(tagList.get(position).getEvalLabelName());
                return textView;
            }

        };
        flowLayout.setAdapter(styleAdapter);
        flowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, com.zhy.view.flowlayout.FlowLayout parent) {
                TagLabelBeanList.TagLabelBean tagListBean = tagList.get(position);
                TextView tagView = (TextView) view;

                if (tagListBean.isSelected() == true) {
                    tagListBean.setSelected(false);
                    tagId.remove(tagListBean.getEvalLabelName());
                    tagView.setTextColor(ContextCompat.getColor(context, R.color.black_8));
                    tagView.setBackgroundColor(ContextCompat.getColor(context, R.color.order_evaluate_gray_color));
                } else {
                    tagListBean.setSelected(true);
                    tagId.add(tagListBean.getEvalLabelName());
                    tagView.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
                    tagView.setBackgroundColor(ContextCompat.getColor(context, R.color.order_pink_color));
                }
                return false;
            }
        });
    }

    /**
     * 保存服务评价
     */
    private void saveServiceEval() {
        // 处理评价标签，多个按逗号分隔
        String tag_str = "";
        if (tagId.size() > 0) {
            for (int i = 0; i < tagId.size(); i++) {
                if (i == tagId.size() - 1) {
                    tag_str += tagId.get(i);
                } else {
                    tag_str += tagId.get(i) + ",";
                }
            }
        }
        HttpParams params = new HttpParams();
        params.put("beautician.content", et_problem.getText().toString()); //美容师评价内容
        params.put("beautician.grade", businessNum);//美容师评价分数
        params.put("beautician.label", tag_str);//评价标签
        params.put("beautician.businessId", businessId);//美容师ID
        params.put("o2oService.content", etSale.getText().toString());//评价内容
        params.put("o2oService.grade", orderNum);//评价分数
        params.put("o2oService.o2oServiceOrderId", o2oServiceOrderId);//评价订单ID
        params.put("beautician.o2oServiceOrderId", o2oServiceOrderId);//评价订单ID
        params.put("o2oService.businessId", beauticianServiceOrderId);//服务项目ID

        HttpUtils.post(Config.SERVICE_SAVE_EVAL, params, new HttpCallBack(this, "数据提交中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (result != null) {
                    String evaluateDetailO2oId = result.optString("evaluateDetailO2oId");
                    if (!AbStrUtil.isEmpty(evaluateDetailO2oId)) {
                        uploadImage(evaluateDetailO2oId);
                    }
                }
                notifyOrderList();
                AppointmentEvaluationActivity.this.finish();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });
    }

    /**
     * 保存培训评价
     */
    private void saveTrainEval() {
        HttpParams params = new HttpParams();
        params.put("content", etSale.getText().toString());//评价内容
        params.put("grade", orderNum);//评价分数
        params.put("o2oServiceOrderId", o2oServiceOrderId);//评价内容
        params.put("businessId", beauticianServiceOrderId);//服务项目ID
        HttpUtils.post(Config.TRAINING_COMMIT_EVALUATE, params, new HttpCallBack(this, "数据提交中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(context,message);
                if (result != null) {
                    String evaluateId = result.optString("evaluateId");
                    if (!AbStrUtil.isEmpty(evaluateId)) {
                        uploadImage(evaluateId);
                    }
                }
                notifyOrderList();
                AppointmentEvaluationActivity.this.finish();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            new AlertDialogFragment.Builder()
                    .setContentText("亲，评价还未完成，您确定要离开？")
                    .setLeftBtnText("确认").setLeftClickCallBack(new AlertDialogFragment.LeftClickCallBack() {
                @Override
                public void dialogLeftBtnClick() {
                    Bimp.tempSelectBitmap.clear();
                    AppointmentEvaluationActivity.this.finish();
                }
            }).setRightBtnText("取消")
                    .build()
                    .show(getSupportFragmentManager(), AlertDialogFragment.TAG);

        }
        return true;
    }

    /**
     * 图片文件选择
     */
    private void localImage() {
        Intent intent = new Intent(context, PhotoFileEvaluateActivity.class);
        if (imageList.size() > 0) {
            intent.putExtra("selectImageSize", imageList.size());
        }
        startActivityForResult(intent, 100);

    }

    /**
     * 拍照
     */
    private void photoGraph() {
        //判断内存卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //创建文件夹
            File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
            //判断是否存在，不存在则创建
            if (!mFolder.exists()) {
                mFolder.mkdirs();
            }
            //删除存在的照片
            File files[] = mFolder.listFiles(); // 声明目录下所有的文件 files[];
            for (int i = files.length - 1; i >= 0; i--) { // 遍历目录下所有的文件
                files[i].delete();// 删除
            }
            //创建新的照片
            String imgName = "mx_" + System.currentTimeMillis() + ".png";
            imgFile = new File(mFolder, imgName);
            //打开相机
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //保存路径
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
            Log.e("TAG", "输出照相路径===" + Uri.fromFile(imgFile));
            startActivityForResult(captureIntent, 101);
        } else {
            AbToastUtil.showToast(context, context.getResources().getString(R.string.account_manage_no_sd_card));
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == 200) {
            //相册选择
            ArrayList<String> fileName = data.getStringArrayListExtra("fileName");
            imageList.addAll(fileName);
            gridAdapter.addPhoto(imageList);
        } else if (requestCode == 101 && resultCode == RESULT_OK) {
            //拍照
            String path = imgFile.getAbsolutePath();
            imageList.add(path);
            gridAdapter.addPhoto(imageList);

        }
    }

    /**
     * 上传评价图片
     * @param evaluateId
     */
    private void uploadImage(String evaluateId) {
        String url = Config.SERVICE_SAVE_EVALIMAGE;
        HttpParams params = new HttpParams();
        params.put("evaluateId", evaluateId);
        if (imageList.size() > 0) {
            List<File> fileList = new ArrayList<>();
            for (int i = 0; i < imageList.size(); i++) {
                File compressFile = getCompressFile(imageList.get(i));
                if (compressFile != null) {
                    fileList.add(new File(imageList.get(i)));
                }
            }
            HttpUtils.postFiles(url, params, "imageFile", fileList, new HttpCallBack(this) {
                @Override
                public void onSucceed(JSONObject result, String code, String message) {
                    Tool.showTextToast(context, message);
                }

                @Override
                public void onError(String code, String message) {
                    Tool.showTextToast(context, message);
                }
            });
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @PermissionGrant(CAMERA_CODE)
    public void requestSdcardSuccess() {
        photoGraph();
    }

    @PermissionDenied(CAMERA_CODE)
    public void requestSdcardFailed() {
        Toast.makeText(activity, "无法启动系统照相机!", Toast.LENGTH_SHORT).show();
    }

    /**
     * 压缩图片上传
     *
     * @param file1
     * @return
     */
    private File getCompressFile(String file1) {
        Log.e(TAG, "文件大小===" + AbFileUtils.getFileSizeFor(new File(file1)));
        try {
            Bitmap bitmap = Bimp.revitionImageSize(file1);
            if (bitmap == null) {
                Log.e(TAG, "图片转bitmap失败");
                return null;
            } else {
                Log.e(TAG, "图片转bitmap成功");
                Bitmap bitmap1 = AbFileUtils.compressImage(bitmap);
                //创建新的照片
                File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
                String imgName = mFolder.getAbsolutePath() + "mx" + System.currentTimeMillis() + ".png";
                File file = AbFileUtils.saveFile(bitmap1, imgName);
                Log.e(TAG, "上传文件大小===" + AbFileUtils.getFileSizeFor(file));
                return file;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadCast);
    }
}
